package com.lagou.filter;

import com.lagou.ExcuteTime;
import com.lagou.Count;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


@Activate(group = {CommonConstants.CONSUMER, CommonConstants.PROVIDER})
public class DubboInvokeFilter implements Filter {

    public static boolean flag = false;
    public static List<ExcuteTime> excuteTimes = new ArrayList<ExcuteTime>();
    public static Date excuteDate = new Date();


    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long startTime = System.currentTimeMillis();
        try {
            // 执行方法
            return invoker.invoke(invocation);
        } finally {
            String methodName = invocation.getMethodName();
            Date currentdate = new Date();
            //System.out.println("invoke time:" + (System.currentTimeMillis() - startTime) + "毫秒");
            //插入数据
            ExcuteTime excuteTime = new ExcuteTime();
            excuteTime.setDoTime(currentdate);
            excuteTime.setTime(System.currentTimeMillis() - startTime);
            excuteTime.setDoMethod(methodName);
            excuteTimes.add(excuteTime);


            //时间比较  判断是否需要执行性能统计任务
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentdate);
            // 将现在的时间滚动固定时长,转换为Date类型赋值
            calendar.add(Calendar.SECOND, -5);
            // 转换为Date类型再赋值
            Date ChangeCurrentTime = calendar.getTime();
            boolean after = ChangeCurrentTime.after(excuteDate);
            if (after) {
                excuteDate = currentdate;
                //开启异步任务  //枷锁，保证只有一个统计任务执行
                if (!flag) {
                    synchronized (Count.class) {
                        if (!flag) {
                            flag = true;
                            try {
                                Count count = new Count(excuteTimes);
                                Thread thread = new Thread(count);
                                thread.run();
                                thread.join(40000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } finally {
                                flag = false;
                            }

                        }
                    }
                }


            }


        }
    }


}
